package com.learning.platform.controller;

import com.learning.platform.dto.ApiResponse;
import com.learning.platform.dto.NoteRequest;
import com.learning.platform.dto.NoteResponse;
import com.learning.platform.service.NoteService;
import jakarta.validation.Valid;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 笔记控制器
 */
@RestController
@RequestMapping("/api/v1/notes")
@PreAuthorize("hasRole('STUDENT') or hasRole('TEACHER') or hasRole('ADMIN')")
public class NoteController {
    
    private final NoteService noteService;
    
    public NoteController(NoteService noteService) {
        this.noteService = noteService;
    }
    
    /**
     * 创建笔记
     */
    @PostMapping
    public ResponseEntity<ApiResponse<NoteResponse>> createNote(
            Authentication authentication,
            @Valid @RequestBody NoteRequest request) {
        
        if (authentication == null || authentication.getPrincipal() == null) {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "用户未认证")
            );
        }
        
        Object principal = authentication.getPrincipal();
        Long userId;
        
        if (principal instanceof com.learning.platform.security.UserPrincipal) {
            userId = ((com.learning.platform.security.UserPrincipal) principal).getUserId();
        } else {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "认证信息格式错误")
            );
        }
        
        NoteResponse response = noteService.createNote(userId, request);
        return ResponseEntity.ok(ApiResponse.success(response, "笔记创建成功"));
    }
    
    /**
     * 更新笔记
     */
    @PutMapping("/{noteId}")
    public ResponseEntity<ApiResponse<NoteResponse>> updateNote(
            Authentication authentication,
            @PathVariable Long noteId,
            @Valid @RequestBody NoteRequest request) {
        if (authentication == null || authentication.getPrincipal() == null) {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "用户未认证")
            );
        }
        
        Object principal = authentication.getPrincipal();
        Long userId;
        
        if (principal instanceof com.learning.platform.security.UserPrincipal) {
            userId = ((com.learning.platform.security.UserPrincipal) principal).getUserId();
        } else {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "认证信息格式错误")
            );
        }
        NoteResponse response = noteService.updateNote(userId, noteId, request);
        
        return ResponseEntity.ok(ApiResponse.success(response, "笔记更新成功"));
    }
    
    /**
     * 删除笔记
     */
    @DeleteMapping("/{noteId}")
    public ResponseEntity<ApiResponse<Void>> deleteNote(
            Authentication authentication,
            @PathVariable Long noteId) {
        if (authentication == null || authentication.getPrincipal() == null) {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "用户未认证")
            );
        }
        
        Object principal = authentication.getPrincipal();
        Long userId;
        
        if (principal instanceof com.learning.platform.security.UserPrincipal) {
            userId = ((com.learning.platform.security.UserPrincipal) principal).getUserId();
        } else {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "认证信息格式错误")
            );
        }
        noteService.deleteNote(userId, noteId);
        
        return ResponseEntity.ok(ApiResponse.success(null, "笔记删除成功"));
    }
    
    /**
     * 获取笔记详情
     */
    @GetMapping("/{noteId}")
    public ResponseEntity<ApiResponse<NoteResponse>> getNoteById(
            Authentication authentication,
            @PathVariable Long noteId) {
        if (authentication == null || authentication.getPrincipal() == null) {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "用户未认证")
            );
        }
        
        Object principal = authentication.getPrincipal();
        Long userId;
        
        if (principal instanceof com.learning.platform.security.UserPrincipal) {
            userId = ((com.learning.platform.security.UserPrincipal) principal).getUserId();
        } else {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "认证信息格式错误")
            );
        }
        NoteResponse response = noteService.getNoteById(userId, noteId);
        
        return ResponseEntity.ok(ApiResponse.success(response));
    }
    
    /**
     * 获取我的所有笔记（分页）
     */
    @GetMapping("/my")
    public ResponseEntity<ApiResponse<Page<NoteResponse>>> getMyNotes(
            Authentication authentication,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(defaultValue = "created") String sortBy) {
        if (authentication == null || authentication.getPrincipal() == null) {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "用户未认证")
            );
        }
        
        Object principal = authentication.getPrincipal();
        Long userId;
        
        if (principal instanceof com.learning.platform.security.UserPrincipal) {
            userId = ((com.learning.platform.security.UserPrincipal) principal).getUserId();
        } else {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "认证信息格式错误")
            );
        }
        Page<NoteResponse> response = noteService.getUserNotes(userId, page, size, sortBy);
        
        return ResponseEntity.ok(ApiResponse.success(response));
    }
    
    /**
     * 获取课程笔记（分页）
     */
    @GetMapping("/course/{courseId}")
    public ResponseEntity<ApiResponse<Page<NoteResponse>>> getCourseNotes(
            Authentication authentication,
            @PathVariable Long courseId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        if (authentication == null || authentication.getPrincipal() == null) {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "用户未认证")
            );
        }
        
        Object principal = authentication.getPrincipal();
        Long userId;
        
        if (principal instanceof com.learning.platform.security.UserPrincipal) {
            userId = ((com.learning.platform.security.UserPrincipal) principal).getUserId();
        } else {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "认证信息格式错误")
            );
        }
        Page<NoteResponse> response = noteService.getCourseNotes(userId, courseId, page, size);
        
        return ResponseEntity.ok(ApiResponse.success(response));
    }
    
    /**
     * 获取章节笔记
     */
    @GetMapping("/lesson/{lessonId}")
    public ResponseEntity<ApiResponse<List<NoteResponse>>> getLessonNotes(
            Authentication authentication,
            @PathVariable Long lessonId,
            @RequestParam Long courseId) {
        if (authentication == null || authentication.getPrincipal() == null) {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "用户未认证")
            );
        }
        
        Object principal = authentication.getPrincipal();
        Long userId;
        
        if (principal instanceof com.learning.platform.security.UserPrincipal) {
            userId = ((com.learning.platform.security.UserPrincipal) principal).getUserId();
        } else {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "认证信息格式错误")
            );
        }
        List<NoteResponse> response = noteService.getLessonNotes(userId, courseId, lessonId);
        
        return ResponseEntity.ok(ApiResponse.success(response));
    }
    
    /**
     * 获取视频时间点笔记
     */
    @GetMapping("/video-timestamps/{lessonId}")
    public ResponseEntity<ApiResponse<List<NoteResponse>>> getVideoTimestampNotes(
            Authentication authentication,
            @PathVariable Long lessonId) {
        if (authentication == null || authentication.getPrincipal() == null) {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "用户未认证")
            );
        }
        
        Object principal = authentication.getPrincipal();
        Long userId;
        
        if (principal instanceof com.learning.platform.security.UserPrincipal) {
            userId = ((com.learning.platform.security.UserPrincipal) principal).getUserId();
        } else {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "认证信息格式错误")
            );
        }
        List<NoteResponse> response = noteService.getVideoTimestampNotes(userId, lessonId);
        
        return ResponseEntity.ok(ApiResponse.success(response));
    }
    
    /**
     * 搜索笔记
     */
    @GetMapping("/search")
    public ResponseEntity<ApiResponse<Page<NoteResponse>>> searchNotes(
            Authentication authentication,
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        if (authentication == null || authentication.getPrincipal() == null) {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "用户未认证")
            );
        }
        
        Object principal = authentication.getPrincipal();
        Long userId;
        
        if (principal instanceof com.learning.platform.security.UserPrincipal) {
            userId = ((com.learning.platform.security.UserPrincipal) principal).getUserId();
        } else {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "认证信息格式错误")
            );
        }
        Page<NoteResponse> response = noteService.searchNotes(userId, keyword, page, size);
        
        return ResponseEntity.ok(ApiResponse.success(response));
    }
    
    /**
     * 根据标签获取笔记
     */
    @GetMapping("/tag/{tag}")
    public ResponseEntity<ApiResponse<List<NoteResponse>>> getNotesByTag(
            Authentication authentication,
            @PathVariable String tag) {
        if (authentication == null || authentication.getPrincipal() == null) {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "用户未认证")
            );
        }
        
        Object principal = authentication.getPrincipal();
        Long userId;
        
        if (principal instanceof com.learning.platform.security.UserPrincipal) {
            userId = ((com.learning.platform.security.UserPrincipal) principal).getUserId();
        } else {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "认证信息格式错误")
            );
        }
        List<NoteResponse> response = noteService.getNotesByTag(userId, tag);
        
        return ResponseEntity.ok(ApiResponse.success(response));
    }
    
    /**
     * 获取常用标签
     */
    @GetMapping("/tags/popular")
    public ResponseEntity<ApiResponse<List<String>>> getPopularTags(
            Authentication authentication,
            @RequestParam(defaultValue = "10") int limit) {
        if (authentication == null || authentication.getPrincipal() == null) {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "用户未认证")
            );
        }
        
        Object principal = authentication.getPrincipal();
        Long userId;
        
        if (principal instanceof com.learning.platform.security.UserPrincipal) {
            userId = ((com.learning.platform.security.UserPrincipal) principal).getUserId();
        } else {
            return ResponseEntity.status(401).body(
                ApiResponse.error(401, "认证信息格式错误")
            );
        }
        List<String> response = noteService.getTopTags(userId, limit);
        
        return ResponseEntity.ok(ApiResponse.success(response));
    }
}
